package com.leyou.goods.service;


import com.leyou.common.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @创建者 Toyn
 * @创建时间 2018/9/19 15:48
 */
@Service
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    public static final String BASE_PATH = "D:\\nginx-1.5.1\\html\\item\\";
    public static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    /**
     * 创建html文件
     */
    public void createHtml(Long spuId){
        PrintWriter writer = null;
        try {
            Map<String, Object> loadModel = goodsService.loadModel(spuId);
            Context context = new Context();
            context.setVariables(loadModel);
            File file = new File(BASE_PATH + spuId + ".html" );
            writer = new PrintWriter(file);
            templateEngine.process("item", context, writer);
        }catch (Exception e){
            LOGGER.error("页面静态化出错 : {}", e, spuId);
        }finally {
            if (null!= writer)
                writer.close();
        }
    }

    public void asyncExcute(Long spuId){
        ThreadUtils.execute(() -> createHtml(spuId));
    }

    //监听静态页面的删除
    public void listenDelete(Long id) {
        File file = new File(BASE_PATH + id + ".html");
        if (file.exists()){
            file.deleteOnExit();
        }

    }
}
